import store from '@/store'
import http from '@/uni_modules/lobster-components/lobster-sdk/js/http.js'
//import config from '@/common/js/config.js'
//import api from '@/common/js/api.js'
import util from '@/uni_modules/lobster-components/lobster-sdk/js/util.js'
import imCommon from '@/uni_modules/lobster-components/lobster-sdk/js/imCommon.js'

import userlist from '@/uni_modules/lobster-components/lobster-sdk/js/userlist.js'
const imLogin = {
	baseP: 300, //最大图片大小
	//初始化sdk
	initSDK(callback) {
		var prm = this.getsdkAppId();
		prm.then(res => {
			//console.log(res);
			imCommon.initSDK(res.data.result, result => {
				//console.log(result)
				store.commit('toggleIsSDKReady', true);
				if (result.code == 'connecting') {
					console.log('sdk connecting...');
				} else if (result.code == 'kicked') {
					console.log('kicked');
					util.showModal("提示", res.msg || '您已经在其他端登录了当前账号', confirm => {
						this.loginout();
						store.commit('logout');
						// uni.removeTabBarBadge({
						// 	index: 2
						// });
						uni.reLaunch({
							url: '/pages/main/index/index'
						});
					}, cancel => {}, false);

				} else if (result.code == 0) { //登录成功 
					store.commit('toggleIsSDKReady', true);
					if (callback)
						callback();
				} else if (result.code == 'expired') {
					console.log('expired');
					util.showModal("提示", res.msg || '登录过期，请重新登录', confirm => {
						this.loginout();
						store.commit('logout');
						// uni.removeTabBarBadge({
						// 	index: 2
						// });
						uni.reLaunch({
							url: '/pages/main/index/index'
						});
					}, cancel => {}, false);
				}
			})
		});
	},
	//登录IM
	login(userId, callback) {
		var promise = this.initData(userId);
		promise.then(res => {
			console.log(res);
			var userSign = res.data.UserSig;
			uni.hideLoading();
			//this.login(userId, sign);
			console.log("login_" + userId + '_' + userSign);
			uni.showLoading({
				title: "正在登录",
				mask: true
			})
			//this.imAccountImport(userId);
			//console.log(store.state.user.myInfo);
		//	this.syncPersionInfo(userId, store.state.user.myInfo);
			imCommon.login(userId, userSign, res => {
				console.log(res);
				uni.hideLoading();
				if (res && res.code == 0) {
					//util.showToast('im登录成功');
					store.commit('toggleIsLogin', true);
					this.addAdvancedMsgListener();
					this.addSignalingListener();
					this.setConversationListener();
					this.setGroupListener(); //群事件
				} else {
					util.showToast(res.msg || 'im登录失败');
				}
				if (callback) {
					callback(res);
				}
			})
		});


	},
	//获取人员相关数据
	initData(userIdentity) {
		console.log(userIdentity);
		return new Promise((reslove, reject) => {
			
			var user= userlist.filter(p=>p.userId== userIdentity);
			if(user && user.length>0){
				var res={};
				res.data={};
				res.data.UserSig=user[0].userSig;
				reslove(res);
			}else{
				var res={};
				res.data={};
				res.data.UserSig='';
				reject(res)
			}
		 
			
			// api.getUserSig(userIdentity).then(res => {
			// 	reslove(res);
			// }).catch(res => {
			// 	util.showToast("getUserSig" + res.msg);
			// 	reject(res)
			// })
		})
	},

	/**
	 * 导入IM云通信账号
	 */
	imAccountImport(userId) {
		var userIdentifier = userId;
		api.imAccountImport({
			workId: config.workId,
			userIdentifier: userIdentifier
		}).then(res => {
			console.log("导入账号成功", res);
		}).catch(res => {
			console.log("导入账号失败", res);
		})
	},
	/**
	 * 同步im信息
	 */
	syncPersionInfo(account, myInfo) {
		//console.log(myInfo);
		var nickName = myInfo.NickName || '';
		var headImg = myInfo.HeadImg || '';
		if (!nickName && !headImg) return;
		api.syncPersionInfo(account, nickName, headImg).then(res => {
			//console.log('33333333');
			//console.log(res);
		}).catch(res => {
			console.log(myInfo);
			console.log(res);
		})
	},

	///监听事件
	addAdvancedMsgListener() {
		imCommon.removeAdvancedMsgListener();
		imCommon.addAdvancedMsgListener(res => {
			console.log(res);
			if (res.code == 'RecvNew') { //收到消息
				var item = res.msg;
				store.commit('pushCurrentMessageList', item);
			} else if (res.code == 'RevokedMessage') { // 消息撤回的通知
				uni.$emit('RevokedMessage', res);
			} else if (res.code == 'ReadReceipt') { //消息已读
				uni.$emit('ReadReceipt', res);
			}
		});
	},
	/**
	 * 信令监听
	 * @callback 回调
	 */
	addSignalingListener() {
		imCommon.removeSignalingListener(res => {});
		imCommon.addSignalingListener(res => {
			console.log("音视频监听啊啊啊");
			console.log(res);
			if (res.code == 100) {
				var data = JSON.parse(res.data);
				if (data.data && data.data.cmd && (data.data.cmd == "requestJoinAnchor" || data.data.cmd ==
						"kickoutJoinAnchor")) {
					return;
				}
				console.log(res);
				//收到邀请 
				//inviteId 邀请id 、
				//inviter、邀请人用户 ID
				//groupId、
				//inviteeList、 被邀请人id列表
				//data 自定义数据
				// var pages= getCurrentPages();
				// util.showModal('邀请',JSON.stringify(pages),aa=>{},bb=>{},false);
				if (store.state.im.ing) {
					var jd = JSON.parse(res.data);
					jd.reason = 'busy';
					imCommon.rejectInvite(res.inviteId, JSON.stringify(jd), res => {});
					return;
				}
				var url = '/pages/im/call?inviteId=' +
					res.inviteId + '&inviter=' + res.inviter + '&data=' + encodeURIComponent(res.data);
				util.navigateTo(url);
			} else if (res.code == 101) {
				//被邀请者接受邀请  inviteId、inviter、data
				//util.showToast("视频已接受")
			} else if (res.code == 102) {

			} else if (res.code == 103) {
				if (store.state.im.ing) {
					let message = '已取消';
					if (res.data) {
						let datainfo = JSON.parse(res.data);
						if (datainfo && datainfo.callType == 'audio') {
							message = '语音已取消';
						} else if (datainfo.callType == 'video') {
							message = '视频已取消';
						}
					}
					util.showToast(message)
					setTimeout(() => {
						util.navigateBack(1);
					}, 1000)
				}
				//uni.$emit("leave");
				//邀请被取消 inviteId、inviter、data
			} else if (res.code == 104) {
				if (store.state.im.ing) {
					//邀请超时 inviteId、inviteeList
					let message = '已超时';
					if (res.data) {
						let datainfo = JSON.parse(res.data);
						if (datainfo && datainfo.callType == 'audio') {
							message = '语音已超时';
						} else if (datainfo.callType == 'video') {
							message = '视频已超时';
						}
					}
					util.showToast(message);
					setTimeout(() => {
						util.navigateBack(1);
					}, 1000)
				}
			}
		});
	},
	/**
	 * 移除监听
	 */
	removeAdvancedMsgListener() {
		imCommon.removeAdvancedMsgListener();
	},
	/**
	 * 会话监听
	 */
	setConversationListener() {
		imCommon.setConversationListener(res => {
			if (res.code == 100) { //同步会话中
				console.log("正在同步会话");
			} else if (res.code == 101) { //同步会话结束
				console.log("同步会话结束");
				console.log(res);
			} else if (res.code == 102) { //同步会话失败
				console.log("同步会话失败");
			} else if (res.code == 103) { //有新的会话
				console.log("有新的会话");
				console.log(res);
				uni.$emit('NewConversation', res);
			} else if (res.code == 104) { //会话有变化
				console.log("会话有变化");
				console.log(res);
				uni.$emit('ConversationChanged', res)
			} else if (res.code == 105) { //未读消息总数发生变化
				console.log(res);
				console.log("未读消息总数发生变化");
				this.getAllMessageCount().then(rs => {
					var sysCount = rs.data.MessageCount;
					var imCount = res.unReadCount;
					var total = parseInt(sysCount) + parseInt(imCount);
					this.setTabBarBadge(total, 3);
				});
			}
		})
	},
	unInitSDK() {
		imCommon.unInitSDK();
		store.commit('toggleIsSDKReady', false);
	},
	//退出登录
	loginout() {
		console.log('logout');
		uni.showLoading({
			title: "正在退出..."
		})
		imCommon.logout(res => {
			console.log(res);
			store.commit('toggleIsLogin', false);
			imCommon.removeAdvancedMsgListener();
			imCommon.removeSignalingListener(res => {});
			//imCommon.unInitSDK();
		})
		uni.hideLoading();
	},

	//获取系统sdkAppId
	getsdkAppId() {
		return new Promise((reslove, reject) => {
			var res ={};
			res.data={};
			res.data.result="1400396242";
			reslove(res)
			// api.GetSystemConfig('SDKAppId').then(res => {
			// 	reslove(res);
			// }).catch(res => {
			// 	util.showToast("getsdkAppId" + res.msg);
			// 	reject(res)
			// })
		})
	},
	//设置角标
	setBadgeNum(num) {
		imCommon.setBadgeNum(num);
	},
	setTabBarBadge(totalCount, index) {
		//console.log("setTabBarBadge:" + totalCount);
		if (totalCount > 0) {
			// uni.setTabBarBadge({
			// 	index: index,
			// 	text: totalCount + ""
			// })
		} else {
			// uni.removeTabBarBadge({
			// 	index: index
			// })
		}
	},
	//获取所有未读消息条数
	unreadMessageCount(success) {
		let query = [];
		let imUnRead = this.getTotalUnreadMessageCount();
		let systemUnRead = this.getAllMessageCount();
		query.push(imUnRead);
		query.push(systemUnRead);
		Promise.all(query).then(res => {
			//console.log(res);
			let res1 = res[0];
			let res2 = res[1];
			let imCount = 0;
			let sysCount = 0;
			let totalCount = 0;
			if (res1.code == 0) {
				imCount = res1.unReadCount;
			}
			if (res2.code == 0) {
				sysCount = res2.data.MessageCount;
			} 
			console.log("系统消息",res2);
			totalCount = parseInt(imCount) + parseInt(sysCount);
			if (success)
				success(totalCount);
			//console.log(totalCount);
			// this.setTabBarBadge(totalCount, 3)
		});
	},

	//获取未读总数
	getTotalUnreadMessageCount() {
		return new Promise((reslove, reject) => {
			imCommon.getTotalUnreadMessageCount(res => {
				reslove(res)
			})
		});
	},
	getAllMessageCount: function() {
		return new Promise((reslove, reject) => {
			api.getUnReadMessageCount().then(res => {
				reslove(res);
			}).catch(res => {
				console.log(res)
			})
		});
	},
	//群组监听器
	setGroupListener() {
		imCommon.setGroupListener(res => {
			if (res.code == '100') { //100 有新成员加入群

			} else if (res.code == '101') { //有成员离开群
			} else if (res.code == '102') { //102 某成员被拉入某群

			} else if (res.code == '103') { //有成员被踢出某群

			} else if (res.code == '104') { //某成员信息发生变更

			} else if (res.code == '105') { //有新的群创建

			} else if (res.code == '106') { //某个已加入的群被解散了

			} else if (res.code == '107') { //自己主动退出群组

			} else if (res.code == '108') { //收到RESTAPI下发的自定义系统消息

			}
		});
	},
}
export default imLogin;